<template>
  <div class="main-container">
    <el-header class="app-header">
      <div class="header-content">
        <router-link :to="{ name: 'Home' }" class="brand">
<!--          <el-image-->
<!--              src="@/assets/health_main.svg"-->
<!--              class="logo"-->
<!--          />-->
          <img style="height: 30px;width: 30px;margin-right: 10px" src="@/assets/health_main.svg">
          <h1 class="title">乐活之道</h1>
        </router-link>

        <!-- 导航菜单 -->
        <el-menu
            :default-active="activeMenu"
            mode="horizontal"
            class="nav-menu"
            @select="handleMenuSelect"
        >
          <el-menu-item index="Home">
            <template #title>
              <el-icon><Reading /></el-icon>
              <span>健康咨询</span>
            </template>
          </el-menu-item>

          <el-menu-item index="Subscribe">
            <template #title>
              <el-icon><Star /></el-icon>
              <span>我的收藏</span>
            </template>
          </el-menu-item>

          <el-menu-item index="Model">
            <template #title>
              <el-icon><DataAnalysis /></el-icon>
              <span>健康指标</span>
            </template>
          </el-menu-item>
        </el-menu>

        <!-- 搜索区 -->
        <div class="search-box">
          <el-input
              v-model="searchInput"
              placeholder="请输入搜索内容"
              clearable
              @keyup.enter="toSearch"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 用户功能区 -->
        <div class="user-area">
          <el-tooltip content="消息通知" placement="bottom">
            <el-badge :value="unreadCount" :max="99" class="notification-badge">
              <el-icon class="notification-icon" @click="toNotice">
                <Bell />
              </el-icon>
            </el-badge>
          </el-tooltip>

          <el-dropdown v-if="isLogin" trigger="hover">
            <div class="user-profile">
              <el-avatar :size="40" :src="loginUser.img" class="user-avatar" />
              <span class="user-name">{{ loginUser.nickName }}</span>
              <el-icon class="arrow-down"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="toPerson">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item divided @click="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button v-else type="text" @click="toLogin" class="login-btn">
            登录 / 注册
          </el-button>
        </div>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <main class="main-content">
      <router-view v-slot="{ Component }">
        <transition name="fade-transform" mode="out-in">
          <component :is="Component" :key="$route.fullPath" />
        </transition>
      </router-view>
    </main>

    <!-- 返回顶部 -->
    <el-backtop :right="80" :bottom="100" />

    <LoginPageDialog ref="loginPageDialog" @reload="reload"></LoginPageDialog>
  </div>
</template>
<script setup>
import {getNoticeList} from "@/api/noticeApi.js";
import {authenticateUser} from "@/api/healthApi.js";
import {authAdminApi} from "@/api/login.js";

import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Reading,
  Star,
  DataAnalysis,
  Search,
  Bell,
  MagicStick,
  User,
  SwitchButton,
  ArrowDown
} from '@element-plus/icons-vue'
import LoginPageDialog from "@/view/login/LoginPageDialog.vue";
// 其他导入保持不变...

const router = useRouter()
const route = useRoute()

const loginPageDialog = ref()

// 计算当前激活菜单
const activeMenu = computed(() => route.name)

// 菜单选择处理
const handleMenuSelect = (index) => {
  router.push({ name: index })
}

//搜索框
const searchInput = ref('')
//是否登录状态
const isLogin = ref(false)
//用户信息
const loginUser = ref({})
//未读信息数
const unreadCount = ref(0)

//开局方法
onMounted(() => {
  initData()
})

//初始化数据
function initData() {
  authLogin()
}

//校验登录
function authLogin() {
  let token = localStorage.getItem('token');
  let user = JSON.parse(localStorage.getItem('healthUser'))
  if (token != null) {
    authenticateUser().catch(err => {
      router.push('/')
      reload()
    })
  }
  if (user != null) {
    isLogin.value = true
    loginUser.value = user
    getNoticeCount()
  }
  openWebSocket()
}

//获取通知数量
function getNoticeCount() {
  getNoticeList().then(res => {
    if (res.data > 99) {
      unreadCount.value = 99
    } else {
      unreadCount.value = res.data
    }
  })
}

//去往搜索页面
function toSearch() {
  if (searchInput.value == '') {
    ElMessage({message: '请输入搜索内容', type: 'warning'})
    return
  }
  router.push({
    name: 'Search',
    query: {
      input: searchInput.value
    }
  })
}

//登录弹窗
function toLogin() {
  loginPageDialog.value.open()
}

//去往个人中心
function toPerson() {
  authAdminApi().then(res=>{
    if(res.data===true){
      router.push({
        name: 'UserManage',
      })
    }else {
      router.push({
        name: 'MyArticles',
      })
    }
  })
}

//登出
function logout() {
  localStorage.removeItem("token")
  localStorage.removeItem('healthUser')
  router.push({name: 'Home'})
  reload()
}

//去往通知页面
function toNotice() {
  let item = localStorage.getItem('token');
  if (item == null || item == undefined) {
    router.push({name: 'Login'})
    return
  }
  unreadCount.value = 0
  router.push({name: 'Notice'})
}


//刷新页面
function reload() {
  setTimeout(() => {
    location.reload()
  }, 500);
}


//webSocket连接
function openWebSocket() {
  let user = localStorage.getItem('healthUser');
  if (user == null) {
    return
  }
  let websocket = new WebSocket('ws://192.168.11.128:8080/api/webSocket/' + JSON.parse(user).id)
  //接收服务器返回数据
  websocket.onmessage = (event) => {
    let message = JSON.parse(event.data);
    ElNotification({
      title: '通知',
      message: message.data,
    })
    getNoticeCount()
  }


}

function toAi(){
  ElMessage({message:'此功能正在开发中',type:"error"})
  // router.push('/ai')
}
</script>
<style scoped>
.main-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

.app-header {
  height: 64px;
  border-bottom: 1px solid var(--el-border-color-light);
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  background: #fff;

  .header-content {
    max-width: 1440px;
    margin: 0 auto;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 24px;
  }
}

.brand {
  display: flex;
  align-items: center;
  margin-right: 40px;
  text-decoration: none;

  .logo {
    width: 36px;
    height: 36px;
    margin-right: 12px;
    transition: transform 0.3s;

    &:hover {
      transform: rotate(-15deg);
    }
  }

  .title {
    font-size: 20px;
    color: var(--el-color-primary);
    margin: 0;
    font-weight: 600;
    letter-spacing: 1px;
  }
}

.nav-menu {
  flex: 1;
  border-bottom: none;
  margin-left: 20px;

  :deep(.el-menu-item) {
    height: 62px;
    font-size: 15px;
    transition: all 0.3s;
    border-bottom: 2px solid transparent;

    &.is-active {
      color: var(--el-color-primary);
      border-bottom-color: var(--el-color-primary);
      background: none;
    }

    &:hover {
      background: var(--el-color-primary-light-9);
    }

    .el-icon {
      margin-right: 8px;
      font-size: 18px;
    }
  }
}

.search-box {
  display: flex;
  align-items: center;
  margin: 0 40px;
  width: 360px;

  .el-input {
    border-radius: 20px;
    transition: all 0.3s;

    &:focus-within {
      box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.1);
    }

    .search-icon {
      color: var(--el-color-primary);
      font-size: 16px;
      margin-left: 8px;
    }
  }

  .ai-btn {
    margin-right: 16px;
    padding: 8px 16px;
    border-radius: 20px;
    background: linear-gradient(135deg, var(--el-color-primary), #6c5ce7);
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
    }

    .el-icon {
      margin-right: 6px;
    }
  }
}

.user-area {
  display: flex;
  align-items: center;
  margin-left: auto;

  .notification-badge {
    margin-right: 24px;

    .notification-icon {
      font-size: 20px;
      color: var(--el-text-color-regular);
      cursor: pointer;
      padding: 8px;
      border-radius: 50%;
      transition: all 0.3s;

      &:hover {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
    }
  }

  .user-profile {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 20px;
    transition: all 0.3s;

    &:hover {
      background: var(--el-color-primary-light-9);

      .user-name {
        color: var(--el-color-primary);
      }
    }

    .user-avatar {
      margin-right: 8px;
    }

    .user-name {
      font-weight: 500;
      margin-right: 4px;
    }

    .arrow-down {
      color: var(--el-text-color-secondary);
      font-size: 12px;
    }
  }

  .login-btn {
    font-weight: 500;
    color: var(--el-color-primary);
    padding: 8px 16px;

    &:hover {
      background: var(--el-color-primary-light-9);
    }
  }
}

.main-content {
  flex: 1;
  overflow-y: auto;
}

.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(20px);
}
</style>
